package sourceagile.server.subversionFileRepository.edit;

import java.util.ArrayList;

import sourceagile.server.doclet.java.tokenizer.JavaTokens;
import sourceagile.server.doclet.java.tokenizer.Tokenize;
import sourceagile.server.doclet.java.tokenizer.TokenizeClassDeclaration;
import sourceagile.server.subversionFileRepository.GetFileContent;

public class EditClassDescription {

	public EditClassDescription(String repositoryURL, String username,
			String password, String filePath, String classDescription,
			String classType, String classStatus) {

		String fileContent = GetFileContent.getContent(repositoryURL, username,
				password, filePath);

		ArrayList<String> classSourceTokenized = Tokenize
				.getClassArrayIndex(fileContent);

		for (int i = 0; i < classSourceTokenized.size(); i++) {

			String token = classSourceTokenized.get(i);

			if (!token.startsWith(JavaTokens.JAVADOC_INIT)
					&& !token.startsWith(JavaTokens.COMMENT)
					&& TokenizeClassDeclaration.getClassTokenPosition(token) >= 0) {

				classSourceTokenized.set(
						i,
						getNewClassJavadoc(classType, classStatus,
								classDescription) + token);

				if (classSourceTokenized.get(i - 1).startsWith(
						JavaTokens.JAVADOC_INIT)) {

					classSourceTokenized.set(i - 1, "");
				}

				break;
			}
		}

		String classSourceUpdated = "";

		for (int i = 0; i < classSourceTokenized.size(); i++) {

			classSourceUpdated += classSourceTokenized.get(i);
		}

		String[] filePathArray = filePath.split("/");

		String fileName = filePathArray[filePathArray.length - 1];

		String path = filePath.substring(0,
				filePath.length() - fileName.length() - 1);

		EditFile.update(repositoryURL, username, password, path, fileName,
				classSourceUpdated);
	}

	private String getNewClassJavadoc(String classType, String classStatus,
			String classDescription) {

		String stringStatus = "";
		if (classStatus != null) {

			stringStatus = "\n * @" + classStatus;
		}

		String stringType = "";

		if (classType != null) {

			stringType = "\n * @" + classType;
		}

		String comment = "\n\n/** \n * " + classDescription + "\n * "
				+ stringStatus + stringType + " \n */";

		return comment;
	}

}
